<?php

namespace Biz\service\Album;

use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;
use Hhz\Redis\otherRedis;
use Biz\cache\album\AlbumWikiCache;
use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumWikiListModel;
use Biz\model\wiki\WikiList as mWikiList;
use Biz\module\Classes\wiki\RelateWiki;
use Doraemon\model\Sysmsg;
use Doraemon\service\User;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;


class AlbumWikiListService
{
    /**
     * 新增或修改清单商品（wiki）
     * @param $wikiList
     * @param $albumId
     * @param $albumTitle
     * @param $uid
     */
    public static function saveAlbumWikiList($wikiList, $albumId, $albumTitle, $uid)
    {
        if ($wikiList) {
            //这里要提前查询清单基本信息 更新用户成长值需要
            $albumInfo = AlbumListService::getAlbumListCache([$albumId])[$albumId] ?? [];
            //这里要提前查询清单商品信息 更新用户成长值需要
            $wikiIdsOld = AlbumWikiListModel::selectByWhere(['album_id'=>$albumId,'status'=>AlbumWikiListModel::STATUS_NORMAL],'wiki_id');

            //先全部删除
            AlbumWikiListModel::updateDataByWhere(['status' => AlbumWikiListModel::STATUS_DELETE],
                ['album_id' => $albumId]);
            //查询该清单已有的wiki列表
            $wikiIdArr = AlbumWikiListModel::selectByWhere(['album_id' => $albumId], 'wiki_id');
            //再添加
            $sort = 1;
            foreach ($wikiList as $value) {
                $wikiId = $value['wiki_id'] ?? 0;
                $objId = $value['obj_id'] ?? '';
                if ($wikiId == 0) { //跳过wiki id 为0的
                    continue;
                }
                $wikiData = [
                    'album_id' => $albumId,
                    'wiki_id' => $wikiId,
                    'uid' => $uid,
                    'content' => $value['content'] ?? '',
                    'obj_id' => $objId,
                    'obj_type' => $objId ? IdParse::getType($objId) : -1,
                    'sort' => $sort,
                    'status' => AlbumWikiListModel::STATUS_NORMAL,
                ];
                if (in_array($wikiId, $wikiIdArr)) {
                    AlbumWikiListModel::updateDataByWhere($wikiData, ['album_id' => $albumId, 'wiki_id' => $wikiId]);
                } else {
                    AlbumWikiListModel::insertData($wikiData);
                    if (!empty($wikiData['obj_id'])) {
                        self::setAlbumWikiObjForOfficial($albumId, $objId);
                    }
                }

                //写入wiki_list
                AlbumWikiListService::upWikiListData($uid , $wikiId);

                $sort++;
            }
            $wikiIds = array_filter(array_unique(array_column($wikiList, 'wiki_id')));
            //写入缓存
            $wikiIdsCache = array_slice($wikiIds, 0, 3);

            $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_W_DETAIL);
            $newRedis->setCache(json_encode([
                'album_title' => $albumTitle,
                'album_id' => $albumId,
                'wiki_ids' => $wikiIdsCache,
            ], JSON_THROW_ON_ERROR),$albumId);

            //更新用户wiki清单
            RelateWiki::changeUserWikiList($uid);

            //更新用户成长值
            $remarks = ['old_quality' => 0, 'new_quality' => $albumInfo['quality'] ?? 0, 'new_wiki_id' => $wikiIds,'old_wiki_id' => $wikiIdsOld];
            \Doraemon\amqp\CommunityQueue::insertQueue(\Doraemon\tools\Creator\GrowthConfig::MQ_QUEUE_URL, [
                'event_name' => \Doraemon\tools\Creator\GrowthConfig::WIKI_GROWTH_WITH_ALBUM_LIST,
                'obj_id' => $albumId,
                'uid' => $uid,
                'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
        }

    }

    /**
     * 删除wiki关联关系
     * @param $albumId
     * @param $uid
     * @return bool
     */
    public static function delAlbumWikiList($albumId, $uid)
    {
        //1、修改状态为删除
        AlbumWikiListModel::updateDataByWhere(['status' => AlbumWikiListModel::STATUS_DELETE], ['album_id' => $albumId, 'uid' => $uid]);
        //2、清除缓存
        $newRedis = new newCache(redisKeys::KEY_B_CACHE_ALBUM_W_DETAIL);
        $newRedis->delCache($albumId);
//        AlbumWikiCache::delData($albumId);
        //3、更新用户wiki清单
        RelateWiki::changeUserWikiList($uid);
        return true;
    }

    /**
     * @param $wikiId
     * @return bool
     */
    public static function afterOffLineWiki($wikiId): bool
    {
        //1、先查询该商品被关联的清单id
        $albumIds = AlbumWikiListModel::selectByWhere(['wiki_id' => $wikiId, 'status' => AlbumWikiListModel::STATUS_NORMAL], 'album_id');
        //2、把wiki状态改为删除
        AlbumWikiListModel::update(['status' => AlbumWikiListModel::STATUS_DELETE], ['wiki_id' => $wikiId]);

        //3、更新此wiki关联的清单的wiki_count 数据
        $wikiCountMap = AlbumWikiListModel::getCountMaps(['album_id' => $albumIds, 'status' => AlbumWikiListModel::STATUS_NORMAL, 'GROUP' => 'album_id']);
        if ($wikiCountMap && is_array($wikiCountMap)) {
            $wikiCountMap = array_column($wikiCountMap, 'cnt', 'album_id');
            if ($albumIds) {
                foreach ($albumIds as $albumId) {
                    $uid = IdParse::getUid($albumId);
                    AlbumListModel::update(['wiki_count' => $wikiCountMap[$albumId] ?? 0],
                        ['album_id' => $albumId, 'uid' => $uid]);
                    RelateWiki::changeUserWikiList($uid);
                }

            }
        }
        return true;

    }

    /**
     * 被好好住官号清单设置内容id，发送系统消息
     * @param $albumId
     * @param $objId
     * @return void
     */
    public static function setAlbumWikiObjForOfficial($albumId, $objId)
    {
        if (empty($albumId) || empty($objId)) {
            return;
        }
        $officialUid = $albumId ? IdParse::getUid($albumId) : 0;
        $uid = $objId ? IdParse::getUid($objId) : 0;
        if (in_array($officialUid, AlbumListModel::DEFAULT_UID_HAOHAOZHU) && !empty($uid)) {
            $albumInfo = AlbumListModel::getAlbumById($albumId);
            if (empty($albumInfo) || $albumInfo['status'] == AlbumListModel::STATUS_DRAFT) {
                return;
            }
            $albumTitle = $albumInfo['title'];
            $officialNick = AlbumListModel::OFFICIAL_UID_MAP[$officialUid] ?? '';
            if ($albumId && $albumTitle && $officialNick) {
                $title = "哇！你推荐的好物被「{$officialNick}」收录至好物清单「{$albumTitle}」啦，快去看看吧>>";
                \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send',
                    [
                        'msgCode' => 0,
                        'to_uid' => $uid,
                        'msgParams' => [
                            'title' => '',
                            'detail' => $title,
                            'link' => Hhzurl::getAlbumDetailNiceLivingLink($albumId),
                            'type' => Sysmsg::TYPE_SYS_MSG,
                        ]
                    ],
                    \Doraemon\cache\Queue::QUEUE_DORAEMON);
            }
        }
    }

    /**
     * 写入wiki_list
     * @param $uid
     * @param $wikiId
     */
    public static function upWikiListData($uid , $wikiId)
    {
        $has = mWikiList::has_master(['uid' => $uid, "wiki_id" => $wikiId]);
        if ($has) {
            mWikiList::updateData(['addtime' => date('Y-m-d H:i:s'), 'status' => mWikiList::STATUS_NORMAL],
                ['uid' => $uid, 'wiki_id' => $wikiId]);
        } else {
            mWikiList::insertData([
                'uid' => $uid,
                'wiki_id' => $wikiId,
                'addtime' => date('Y-m-d H:i:s'),
                'status' => mWikiList::STATUS_NORMAL,
            ]);
        }
    }

}